<?php
/**
 *  用户模块
 * User: 梁晓伟  lxw11109@gmail.com
 * Date: 2017-09-15
 * Time: 19:16
 */

namespace App\Http\Controllers\Api\V1\Front\User;


use App\Http\Controllers\Controller;
use App\Models\Account;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cookie;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Validator;


class UserController extends Controller
{
    public function index(){
        $data['userList'] = Account::select('userId','username','phoneNumber')->paginate(20);
        return $this->apiResponse($data);
    }

    public function login(Request $request)
    {
       $data = $request->all();
       $validator = Validator::make($data, [
           'user'       =>'required',
           'password'          =>'required|min:6'
       ]);
       if($validator->fails()){
           return $this->apiResponse('', config('errorCode.INVALID_REQ_PARAMS'));
       }
       $data['phoneNumber'] = $data['user'];
       $data['passwords'] = $data['password'];
       $data['password'] = md5(md5($data['passwords']));
       $time = date("Y-m-d H:i:s");
       $ip = getIp();
       unset($data['user']);
       $user = Account::where($data)->first();
       Account::where($data)->update(['lastloginip'=>$ip,'lastlogintime'=>$time]);
       if (!$user){
            $data['username'] = $data['phoneNumber'];
            unset($data['phoneNumber']);
            $user = Account::where($data)->first();
           Account::where($data)->update(['lastloginip'=>$ip,'lastlogintime'=>$time]);

           if(!$user){
               return $this->apiResponse('', config('errorCode.NAME_PASSWORD_NOT_MATCH'));
           }
       }
       $cookieTime = 5;
       $username = Cookie::make('username',$user['username'],$cookieTime);
       $userId = Cookie::make('userId',$user['userId'],$cookieTime);
       return $this->apiResponse($user)->withCookie($username)->withCookie($userId);

    }

    public function register(Request $request)
    {
        $data = $request->all();
        $validator = Validator::make($data, [
            'phoneNumber'       =>'regex:/^1[34578][0-9]{9}$/',
            'password'          =>'required|min:6',
            'username'          =>'required',

        ]);
        if($validator->fails()){
            return $this->apiResponse('', config('errorCode.INVALID_REQ_PARAMS'));
        }



        $status = Account::where('phoneNumber',$data['phoneNumber'])->first();
        if($status){
            return $this->apiResponse('', config('errorCode.PHONENUMBER_EXISTA'));
        }
        $status = Account::where('username',$data['username'])->first();
        if($status){
            return $this->apiResponse('', config('errorCode.USERNAME_ALREADY'));
        }

        $data['salt'] = $this->myRand();
        $data['regip'] = getIp();
        $data['regdate'] = time();
        $data['passwords'] = $data['password'];
        $data['password'] = md5(md5($data['passwords']));
        unset($data['code']);

        $status = Account::create($data);
//        return $this->apiResponse($status);
        if(!$status){
            return $this->apiResponse('', config('errorCode.REGIST_FAILED'));
        }
        $user = Account::where('phoneNumber',$data['phoneNumber'])->first();

        $cookieTime = 5;
        $username = Cookie::make('username',$user['username'],$cookieTime);
        $userId = Cookie::make('userId',$user['userId'],$cookieTime);
        return $this->apiResponse($user)->withCookie($username)->withCookie($userId);
    }

    public function check(Request $request){
        $cookies = $request->all();
        $user = Account::find($cookies['userId']);
        if ( $user['username'] == $cookies['username'] && $user['userId'] == $cookies['userId']){
            return $this->apiResponse(true);
        }
    }

    function myRand(){
        if(PHP_VERSION < '4.2.0'){
            srand();
        }
        $randArr = array();
        for($i = 0; $i < 3; $i++){
            $randArr[$i] = rand(0, 9);
            $randArr[$i + 3] = chr(rand(0, 25) + 97);
        }
        shuffle($randArr);
        return implode('', $randArr);
    }

    public function show($userId){
        $data =  Account::select("avatar","sina","qq","wechat","birthday","gender","province","city","district","work","username","phoneNumber","email")->find($userId);
        return $this->apiResponse($data);
    }

    public function store(Request $request){
        $data = $request->all();
        $validator = Validator::make($data, [
            'userId' => 'required|integer'
        ]);
        $username = @$data['username'];
        if($validator->fails()){
            return $this->apiResponse('', config('errorCode.INVALID_REQ_PARAMS'));
        }
        $userId = $data['userId'];
        unset($data['userId']);
//        unset($data['username']);
        unset($data['password']);
        unset($data['passwords']);
        unset($data['salt']);
        $status = Account::where('username',$username)->first();
        if ($status){
            if ($status['userId'] != $userId) {
                return $this->apiResponse('', config('errorCode.Usr_ALREADY'));
            }
        }
        if ($userId){
            $status = Account::where('userId', $userId)->update($data);
            if (!$status) {
                return $this->apiResponse('', config('errorCode.EDI_REQ_FAILED'));
            }else{
                return $this->apiResponse(true);
            }
        }
    }

    public function update(Request $request ,$userId){
        $data = $request->only('userId','oldPassword','newPassword');
        $validator = Validator::make($data,[
            'oldPassword'    => 'required',
            'newPassword'    => 'required'
        ]);
        if ($validator->fails()) {
            return $this->apiResponse('', config('errorCode.INVALID_REQ_PARAMS'));
        }
        //判断密码是否正确
        $status = Account::where(['userId'=>$userId,'passwords'=>$data['oldPassword']])->first();
        if($status){//成功
            $status = Account::where(['userId'=>$userId])->update(['passwords'=>$data['newPassword'],'password'=>md5(md5($data['newPassword']))]);
            if($status){//更新成功
                return $this->apiResponse(true);
            }else{
                return $this->apiResponse('', config('errorCode.PASSWORD_UPDATE_FAILED'));
            }
        }else{//失败
            return $this->apiResponse('', config('errorCode.OLD_PASSWORD_FALSE'));
        }
    }

    public function findPassword(Request $request){
        $data = $request->only('phoneNumber','password','code');
        $validator = Validator::make($data,[
            'phoneNumber'       =>'regex:/^1[34578][0-9]{9}$/',
            'password'          =>'required|min:6',
            'code'              =>'integer|required'
        ]);
        if ($validator->fails()) {
            return $this->apiResponse('', config('errorCode.INVALID_REQ_PARAMS'));
        }

        $code =  \RedisDB::get($data['phoneNumber']);
        if ($data['code'] != $code){
            return $this->apiResponse('', config('errorCode.CODE_ERROR'));
        }
        unset($data['code']);
        $status = Account::where('phoneNumber','=',$data['phoneNumber'])->first();
        if ($status) {
            $status = Account::where(['phoneNumber' => $data['phoneNumber']])->update(['passwords' => $data['password'], 'password' => md5(md5($data['password']))]);
            if ($status) {//更新成功
                return $this->apiResponse(true);
            } else {
                return $this->apiResponse('', config('errorCode.PASSWORD_UPDATE_FAILED'));
            }
        }else{
            return $this->apiResponse('', config('errorCode.USER_NOT_FIND'));
        }

    }

    public function userDetail($userId){
        $data =  Account::select("username","passwords","avatar","sina","qq","wechat","birthday","gender","province","city","district","work","username","phoneNumber","email")->find($userId);
        return $this->apiResponse($data);
    }

    function authcode($string, $operation = 'DECODE', $key = '', $expiry = 0) {

        $ckey_length = 4;

        $key = md5($key ? $key : 'u2jaj4l517HcN2r7C0U5pdEdK2f7Pam1u06e02RbC3D6t6yfDfZeM6A4n5l8g7c4');
        $keya = md5(substr($key, 0, 16));
        $keyb = md5(substr($key, 16, 16));
        $keyc = $ckey_length ? ($operation == 'DECODE' ? substr($string, 0, $ckey_length): substr(md5(microtime()), -$ckey_length)) : '';

        $cryptkey = $keya.md5($keya.$keyc);
        $key_length = strlen($cryptkey);

        $string = $operation == 'DECODE' ? base64_decode(substr($string, $ckey_length)) : sprintf('%010d', $expiry ? $expiry + time() : 0).substr(md5($string.$keyb), 0, 16).$string;
        $string_length = strlen($string);

        $result = '';
        $box = range(0, 255);

        $rndkey = array();
        for($i = 0; $i <= 255; $i++) {
            $rndkey[$i] = ord($cryptkey[$i % $key_length]);
        }

        for($j = $i = 0; $i < 256; $i++) {
            $j = ($j + $box[$i] + $rndkey[$i]) % 256;
            $tmp = $box[$i];
            $box[$i] = $box[$j];
            $box[$j] = $tmp;
        }

        for($a = $j = $i = 0; $i < $string_length; $i++) {
            $a = ($a + 1) % 256;
            $j = ($j + $box[$a]) % 256;
            $tmp = $box[$a];
            $box[$a] = $box[$j];
            $box[$j] = $tmp;
            $result .= chr(ord($string[$i]) ^ ($box[($box[$a] + $box[$j]) % 256]));
        }

        if($operation == 'DECODE') {
            if((substr($result, 0, 10) == 0 || substr($result, 0, 10) - time() > 0) && substr($result, 10, 16) == substr(md5(substr($result, 26).$keyb), 0, 16)) {
                return substr($result, 26);
            } else {
                return '';
            }
        } else {
            return $keyc.str_replace('=', '', base64_encode($result));
        }

    }

}